iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 8
0
自我挑戰組

各種筆記系列 第 8

[Kata] Clojure - Day 8

  • 分享至 

  • xImage
  •  

How do I compare numbers?

What could be easier than comparing integer numbers? However, the given piece of code doesn't recognize some of the special numbers for a reason to be found. Your task is to find the bug and eliminate it.

使用下列函式比較數字時,(* 42 42) 並沒有回傳 everything squared,要修掉 bug

(ns how-do-i-compare)

(defn what-is [x]
  (cond
    (identical? x 42) "everything"
    (identical? x (* 42 42)) "everything squared"
    :else "nothing"))
(ns how-do-i-compare-test
  (:require [clojure.test :refer :all]
            [how-do-i-compare :refer [what-is]]))

(deftest tests
  (are [x answer] (= (what-is x) answer)
    0 "nothing"
    123 "nothing"
    -1 "nothing"
    42 "everything"
    (* 42 42) "everything squared"
  ))

Solution

identical? 判斷兩個參數是否為同一個 object; = 判斷兩個是否有一樣的值

(ns how-do-i-compare)

(defn what-is [x]
  (cond
    (= x 42) "everything"
    (= x (* 42 42)) "everything squared"
    :else "nothing"))
(def x 123)
(def y 123)
(= x y)             ;; true
(identical? x y)    ;; true
(= x x)             ;; true
(identical? x x)    ;; true
(= x 123)           ;; true
(identical? x 123)  ;; true
(def x "123")
(def y "123")
(= x y)           ;; true
(identical? x y)  ;; true
(def x (String. "123"))
(def y (String. "123"))
(= x y)          ;; true
(identical? x y) ;; false
(def x (list 1 2 3))
(def y (list 1 2 3))
(= x y)          ;; true
(identical? x y) ;; false

上一篇
[Kata] Clojure - Day 7
下一篇
[Kata] Clojure - Day 9
系列文
各種筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言